package com.eshipenet.shipnet.commplanrpc.server;


import akka.actor.AbstractActor;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.eshipenet.shipnet.commplanrpc.grpc.CommCardRepoGrpcImpl;
import com.eshipenet.shipnet.commplanrpc.grpc.CommPlanRepoGrpcImpl;
import com.eshipenet.shipnet.commplanrpc.ignite.CommPlanIgnite;
import com.eshipenet.shipnet.commplanrpc.service.CommCardService;
import com.eshipenet.shipnet.commplanrpc.service.CommPlanIdGenerator;
import com.eshipenet.shipnet.commplanrpc.service.CommPlanIdGeneratorImpl;
import com.eshipenet.shipnet.commplanrpc.service.CommPlanService;
import io.grpc.ServerBuilder;
import io.grpc.protobuf.services.ProtoReflectionService;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


class CommPlanActor extends AbstractActor {

    static Props props() {
        return Props.create(CommPlanActor.class, CommPlanActor::new);
    }

    @Override
    public void preStart() throws Exception {

        Ignite ignite = Ignition.ignite("CommPlan");

        String commPlanGeneratorName = "CommPlanIdGenerator";
        ignite.services().deployClusterSingleton(commPlanGeneratorName, new CommPlanIdGeneratorImpl(1, 1));
        CommPlanIdGenerator commPlanIdGenerator = ignite.services().service(commPlanGeneratorName);
        CommPlanService commPlanService = ignite.services().service("CommPlanService");

        String commCardGeneratorName = "CommCardIdGenerator";
        ignite.services().deployClusterSingleton(commCardGeneratorName, new CommPlanIdGeneratorImpl(1, 1));
        CommPlanIdGenerator commCardIdGenerator = ignite.services().service(commCardGeneratorName);
        CommCardService commCardService = ignite.services().service("CommCardService");

        ServerBuilder.forPort(50051)
                    .addService(new CommPlanRepoGrpcImpl(commPlanService,commPlanIdGenerator))
                     .addService(new CommCardRepoGrpcImpl(commCardService,commCardIdGenerator))
                .addService(ProtoReflectionService.newInstance())
                .build()
                .start();

    }

    @Override
    public void postStop() {
        System.out.println("stopped...");
    }


    @Override
    public Receive createReceive() {
        return receiveBuilder().matchAny(t -> {
            getSender().tell(t, getSelf());
            //停止
            //getContext().stop(getSelf());
        }).build();

    }


    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger("CommPlanActor");
        logger.debug("ignite start");
        CommPlanIgnite.ignite();
        ActorSystem system = ActorSystem.create("commplanrpc");
        system.actorOf(CommPlanActor.props(), "RPCServer");
    }
}





